<?php
/**
 * 文件上传API逻辑
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\api\logic;

use app\api\logic\ApiBase;

class Upload extends ApiBase
{
    /**
     * 基类初始化
     */
    public function __construct()
    {
        parent::__construct();
    }
    
    /**
     * 上传图片
     */
    public function uploadImage($data = [])
    {
        try {
            // JWT解析用户信息
            $token = $data['user_token'] ?? '';
            if (!empty($token)) {
                $userData = get_user_by_token($token);
                $data['user_id'] = $userData['user_id'];
            }
            
            // 调用File逻辑层的图片上传方法
            $result = $this->logicFile->pictureUpload('file');
            
            if ($result) {
                // 操作成功，直接返回数据
                return $result;
            } else {
                // 操作失败，抛出异常让Controller层处理
                throw new \Exception('上传失败');
            }
            
        } catch (\Exception $e) {
            // 抛出异常让Controller层的apiReturn统一处理
            throw new \Exception('上传失败：' . $e->getMessage());
        }
    }
    
    /**
     * 上传文件
     */
    public function uploadFile($data = [])
    {
        try {
            // JWT解析用户信息
            $token = $data['user_token'] ?? '';
            if (!empty($token)) {
                $userData = get_user_by_token($token);
                $data['user_id'] = $userData['user_id'];
            }
            
            // 调用File逻辑层的文件上传方法
            $result = $this->logicFile->fileUpload('file');
            
            if ($result) {
                // 操作成功，直接返回数据
                return $result;
            } else {
                // 操作失败，抛出异常让Controller层处理
                throw new \Exception('上传失败');
            }
            
        } catch (\Exception $e) {
            // 抛出异常让Controller层的apiReturn统一处理
            throw new \Exception('上传失败：' . $e->getMessage());
        }
    }
    
    /**
     * 删除文件
     */
    public function deleteFile($data = [])
    {
        try {
            // JWT解析用户信息
            $token = $data['user_token'] ?? '';
            if (!empty($token)) {
                $userData = get_user_by_token($token);
                $data['user_id'] = $userData['user_id'];
            }

            $fileId = $data['file_id'] ?? 0;
            $fileType = $data['file_type'] ?? 'image'; // image 或 file

            if (!$fileId) {
                throw new \Exception('文件ID不能为空');
            }

            // 删除云存储文件（如配置了存储驱动）
            $storage_driver = config('storage_driver');
            if (!empty($storage_driver)) {
                $driver = SYS_DRIVER_DIR_NAME . $storage_driver;
                if ($fileType === 'image') {
                    $this->serviceStorage->$driver->deletePicture($fileId);
                } else {
                    $this->serviceStorage->$driver->deleteFile($fileId);
                }
            }

            // 删除数据库记录
            $model = $fileType === 'image' ? $this->modelPicture : $this->modelFile;
            $deleted = $model->deleteInfo(['id' => $fileId], true);

            if ($deleted) {
                return ['deleted' => true, 'file_id' => $fileId];
            }

            throw new \Exception('删除失败');

        } catch (\Exception $e) {
            // 抛出异常让Controller层的apiReturn统一处理
            throw new \Exception('删除失败：' . $e->getMessage());
        }
    }
}
